//
//  SWPageViewController.swift
//  YiyaPuzzleDemo
//  单页
//  Created by linhan on 16/9/28.
//  Copyright © 2016年 test. All rights reserved.
//

import Foundation
import UIKit
class SWPageViewController: SWBaseViewController,SWPagePhotoViewDelegate,ImagePickerHelperDelegate,SWBookPhotoEditorViewControllerDelegate,UIGestureRecognizerDelegate
{
    var data:AnyObject?
    var page:SWPage?{
        didSet{
            if page != oldValue
            {
                pageUpdated()
            }
        }//end didSet
    }
    
    var previewMode:Bool = false
    
    //是否允许拖动
    private let PanEnable:Bool = false
    
    //返回这些PhotoView在window上的区域
    private var _photoViewRects:[SWPagePhotoViewRect] = []
    var photoViewRects:[SWPagePhotoViewRect]{
        if _photoViewRects.count == 0
        {
            let views:[SWPagePhotoView] = _photoViewContainer.subviews.flatMap({$0 as? SWPagePhotoView})
            for photoView in views
            {
                let keyWindow = UIApplication.shared.keyWindow
                let rect = photoView.superview?.convert(photoView.frame, toView: keyWindow) ?? CGRectZero
                //print("photoView rect:", rect)
                _photoViewRects.append((view:photoView, rect:rect))
            }
        }
        return _photoViewRects
    }
    
    
    
    private var _inited:Bool = false
    private var _imageView:UIImageView = UIImageView()
    private var _photoViews:[SWPagePhotoView] = []
    private var _photoViewContainer:SWPagePhotoViewContainer = SWPagePhotoViewContainer()
    private var _textContainer = SWPageTextContainer()
    private var _popupTextInput:SWPopupTextInput = SWPopupTextInput()
    
    private var _imagePicker:ImagePickerHelper?
    private var _photoView:SWPagePhotoView?
    private var _textIndex:Int = 0
    private var _text:SWText?
    
    deinit
    {
        NotificationCenter.default.removeObserver(self)
        print("DEINIT SWPageViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        _photoViewRects = []
        //deleting = false
        SWDragManager.sharedManager().deleting = false
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if let read = page?.read,!read
        {
            page?.read = true
            save()
        }
    }
    
    override func viewWillLayoutFirstTime() {
        setup()
    }
    
    
    
    private func setup()
    {
        //print("layout", view.frame)
        view.backgroundColor = UIColor.white
        
        _imagePicker = ImagePickerHelper()
        _imagePicker?.delegate = self
        _imagePicker?.containerViewController = self
        _imagePicker?.cropSize = CGSizeZero
        
        _popupTextInput.setup(container: view, containerRect: UIScreen.main.bounds)
        
        //点击在空白区域时，隐藏删除按钮
        //let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(backgroundTapped))
        //tapGesture.delegate = self
        //view.addGestureRecognizer(tapGesture)
        
        //照片层
        _photoViewContainer.frame = view.bounds
        view.addSubview(_photoViewContainer)
        
        //模板层，照片区域镂空
        _imageView.frame = view.bounds
        view.addSubview(_imageView)
        
        //文字层
        _textContainer.frame = view.bounds
        view.addSubview(_textContainer)
        
        NotificationCenter.default.addObserver(forName: NotificationName.DownloadTaskComplete, object: nil, queue: OperationQueue.main, using: {[weak self] notification in
            self?.downloadTaskCompleteNotification(notification)
        })
        
        NotificationCenter.default.addObserver(self, selector: #selector(pageUpdatedNotification(_:)), name: NotificationName.BookPageUpdated, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(photoUpdatedNotification(_:)), name: NotificationName.BookPagePhotoUpdated, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(pageCompletedManualNotification(_:)), name: NotificationName.PageCompletedManual, object: nil)
        
        _inited = true
        if let _ = page{
            pageUpdated()
        }
    }
    
    private func loadData()
    {
        
    }
    
    private func downloadTaskCompleteNotification(_ notification:Notification)
    {
        if let remoteURL = notification.userInfo?[SWKey.remoteURL] as? String, remoteURL == page?.previewBgURL
        {
            updateBGView()
        }
    }
    
    //背景图加载完成，进行更新
    private func pageUpdated()
    {
        guard let page = page,_inited && !page.whitespace else{
            return
        }
        
        reloadPhotoView()
        
        if let previewBgURL = page.previewBgURL
        {
            if let image = SWDownloadManager.sharedManager().getImage(page.previewBgURL)
            {
                _imageView.image = image
            }
            else
            {
                //当展示当前页时，将此页的下载权重提到最高
                let task = SWDownloadTask(url: previewBgURL)
                SWDownloadManager.sharedManager().addTask(task, priority: .veryHigh)
            }
        }
        
        //当前页面还没有照片，如果这个页面是事件类型，则自动从事件中导入
        page.loadPhotoFromEvent()
    }
    
    private func updateBGView()
    {
        if let page = page
        {
            _imageView.image = SWDownloadManager.sharedManager().getImage(page.previewBgURL)
        }
    }
    
    private func reloadPhotoView()
    {
        _photoViewContainer.removeAllSubview()
        if let photos:[SWPhoto] = page?.photos?.flatMap({$0 as? SWPhoto})
        {
            for (index, photo) in photos.enumerated()
            {
                let rect = _photoViewContainer.bounds
                let x:CGFloat = rect.width * CGFloat(photo.xPercent)
                let y:CGFloat = rect.height * CGFloat(photo.yPercent)
                let width:CGFloat = rect.width * CGFloat(photo.widthPercent)
                let height:CGFloat = rect.height * CGFloat(photo.heightPercent)
                let photoViewRect = CGRectMake(x, y, width, height)
                
                let photoView = SWPagePhotoView(photo:photo)
                photoView.tag = index
                photoView.previewMode = previewMode
                photoView.frame = photoViewRect
                photoView.delegate = self
                _photoViewContainer.addSubview(photoView)
                
                if !previewMode && PanEnable
                {
                    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(photoViewPan(_:)))
                    photoView.addGestureRecognizer(panGesture)
                }
            }
        }
        
        _textContainer.removeAllSubview()
        if let texts:[SWText] = page?.texts?.flatMap({$0 as? SWText})
        {
            for (index, text) in texts.enumerated()
            {
                let rect = _photoViewContainer.bounds
                let x:CGFloat = rect.width * CGFloat(text.xPercent)
                let y:CGFloat = rect.height * CGFloat(text.yPercent)
                let width:CGFloat = rect.width * CGFloat(text.widthPercent)
                let height:CGFloat = rect.height * CGFloat(text.heightPercent)
                let labelRect = CGRectMake(x, y, width, height)
                
                let textColor = UIColor(hex: text.textColor ??? "0x0")
                let textContent:String = text.text ?? ""
                
                
                let label:UILabel = UILabel()
                label.tag = index
                label.frame = labelRect
                label.numberOfLines = 0
                label.textColor = textColor
                label.isUserInteractionEnabled = true
                _textContainer.addSubview(label)
                setLabelText(label, content: textContent)
                
                if !previewMode
                {
                    let labelTapGesture = UITapGestureRecognizer(target: self, action: #selector(labelTapped(_:)))
                    label.addGestureRecognizer(labelTapGesture)
                }
                
            }//end for
        }//end texts
        
    }
    
    private func setLabelText(_ label:UILabel, content:String)
    {
        let rect = _photoViewContainer.bounds
        let PPRatio:CGFloat = 300 / 72
        let printFontSize:CGFloat = CGFloat(SW.Config.Template.FontSize) * PPRatio
        
        let previewRatio:CGFloat = (rect.height) / SW.Config.BookSinglePageSize.height
        
        var fontSize = floor(CGFloat(SW.Config.Template.FontSize) * previewRatio)
        fontSize = printFontSize * previewRatio
        let TextLeading = SW.Config.Template.TextLeading * PPRatio * previewRatio
        
        //print("fontSize:", previewRatio, fontSize, TextLeading)
        let font = UIFont.systemFont(ofSize: fontSize)
        //let contentHeight:CGFloat = StringUtil.getStringHeight(content, font: font, width: width, lineSpacing:TextLeading)
        let attributedString:NSMutableAttributedString = NSMutableAttributedString(string:content)
        let textRange = NSRange(location: 0, length: content.length)
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineBreakMode = .byTruncatingMiddle
        paragraphStyle.lineSpacing = TextLeading
        attributedString.addAttribute(NSFontAttributeName, value: font, range: textRange)
        attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: textRange)
        
        
        label.font = font
        label.attributedText = attributedString
    }
    
    //页面变更过程中添加到生成队列中
    private func addGenerationTask()
    {
        if let page = page{
            let task = SWGenerationTask(page:page)
            task.uploadPreviewRightNow = true
            SWPageManager.sharedManager().addTask(task, autoStart: true)
        }
    }
    
    private func exchangeCancel()
    {
        
    }
    
    private func exchangePhoto(_ startView:SWPagePhotoView, endView:SWPagePhotoView)
    {
        SWPhoto.swapContent(startView.photo, rhs: endView.photo)
        startView.swapContent(true)
        endView.swapContent()
    }
    
    //更新ImageID对应的PhotoView
    private func updatePhotoView(_ imageID:String)
    {
        let photoViews = _photoViewContainer.subviews.flatMap({$0 as? SWPagePhotoView})
        if let index = photoViews.index(where: {$0.photo.imageID ?? "" == imageID}),
            let photoView = photoViews.valueAt(index)
        {
            photoView.imageViewUpdate(true)
        }
    }
    
    //更新本页所有PhotoView
    private func updateAllPhotoView()
    {
        for photoView in _photoViewContainer.subviews
        {
            (photoView as? SWPagePhotoView)?.imageViewUpdate(false)
        }
    }
    
    //对当前的修改进行保存
    private func save()
    {
        if let page = page{
            SWBookManager.sharedManager().save(page:page)
        }
    }
    
    
    //MARK ============================================================================================
    //==============================            Delegate           ===============================
    //=================================================================================================
    
    func pagePhotoViewSingleTap(_ photoView:SWPagePhotoView)
    {
        if previewMode{
            return
        }
        
        _photoView = photoView
        //检查本地照片是否存在
        if let imageID = photoView.photo.imageID, imageID != ""
        {
            //编辑这张图片
            let editorViewController = SWBookPhotoEditorViewController(imageID: imageID)
            editorViewController.delegate = self
            //present(editorViewController, animated: true, completion: nil)
            SWMainApplication.sharedApplication.rootViewController?.present(editorViewController, animated: true, completion: nil)
            //UIApplication.shared.windows.first?.rootViewController
        }
        else
        {
            _imagePicker?.presentPhotoLibraryPickerController(allowsEditing: false)
        }
    }
    
    //图片交换
    func pagePhotoViewSwap(_ photoView:SWPagePhotoView)
    {
        save()
        addGenerationTask()
    }
    
    //长按
    func pagePhotoViewLongPress(_ photoView:SWPagePhotoView)
    {
        guard let imageID = photoView.photo.imageID, imageID != "" else {
            print("pagePhotoViewLongPress imageID nil")
            return
        }
        //SWDragManager.sharedManager().deleting = true
    }
    
    //删除
    func pagePhotoViewDelete(_ photoView:SWPagePhotoView)
    {
        Alert.show("", message: "是否删除照片？", buttons: ["删除","取消"], closeHandler: {buttonIndex in
            if buttonIndex == 0
            {
                SWDragManager.sharedManager().deleting = false
                if let imageID = photoView.photo.imageID
                {
                    SWBookAssetManager.sharedManager().removePhoto(imageID)
                }
                photoView.photo.imageID = nil
                photoView.imageViewUpdate()
                self.save()
                self.addGenerationTask()
            }
        })
    }
    
    //MARK ================================= ImagePickerHelperDelegate =========================
    func imagePickerDidFinishPickingImage(image:UIImage?)
    {
        guard let image = image,let data = UIImageJPEGRepresentation(image, 0.9) else{
            return
        }
        trace("原图", image.size, image.scale)
        let imageID = SWBookAssetManager.sharedManager().addPhoto(image, data: data)
        _photoView?.photo.imageID = imageID
        _photoView?.image = image
        _photoView?.imageViewUpdate(false)
        save()
        addGenerationTask()
        //写入时间
        let photoImportedTime:Int = page?.photoImportedTime ?? 0
        if photoImportedTime == 0
        {
            page?.photoImportedTime = Int(Date().timeIntervalSince1970)
        }
        
        //ioQueue写入完成再检查
        SWBookAssetManager.sharedManager().ioQueue.async {
            //手动填满后对外通知，翻到下一页
            if let page = self.page,
                let pageID = page.pageID,page.completeness && pageID != ""
            {
                SWNotificationCenter.post(name: NotificationName.PageCompletedManual, object: nil, userInfo: [SWKey.pageID:pageID])
            }
        }
    }
    
    //MARK ================================= SWBookPhotoEditorViewControllerDelegate =========================
    func photoEditorViewControllerProcessComplete(_ viewController:SWBookPhotoEditorViewController, image:UIImage, imageID:String)
    {
        //updatePhotoView(imageID)
        addGenerationTask()
    }
    
    //MARK ================================= UIGestureRecognizerDelegate =========================
//    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool
//    {
//        var shouldSimultaneously:Bool = true
//        if gestureRecognizer is UITapGestureRecognizer
//            && otherGestureRecognizer is UITapGestureRecognizer
//            && gestureRecognizer.view == _photoViewContainer
//            && otherGestureRecognizer.view == view.superview
//            && SWDragManager.sharedManager().deleting
//        {
//            shouldSimultaneously = false
//        }
//        return shouldSimultaneously
//    }
    
    @objc private func photoViewPan(_ recognizer:UIPanGestureRecognizer)
    {
        //空格子 等情况下无法移动
        //let deleting = SWDragManager.sharedManager().deleting
        // && !deleting
        guard let photoView = recognizer.view as? SWPagePhotoView,
              let imageID = photoView.photo.imageID, imageID != "" else
        {
            return
        }
        
        let point = recognizer.location(in: UIApplication.shared.keyWindow)
        if recognizer.state == .began
        {
            let cursor = recognizer.view?.snapshotView(afterScreenUpdates: false)
            cursor?.isUserInteractionEnabled = false
            cursor?.center = point
            cursor?.alpha = 0.7
            if let cursor = cursor
            {
                SWDragManager.sharedManager().showCursor(cursor)
            }
            SWDragManager.sharedManager().startView = recognizer.view
            SWDragManager.sharedManager().deleting = true
        }
        else if recognizer.state == .changed
        {
            SWDragManager.sharedManager().cursor?.center = point
        }
        else if recognizer.state == .ended
        {
            SWDragManager.sharedManager().hideCursor()
            SWDragManager.sharedManager().deleting = false
            
            if let startView = SWDragManager.sharedManager().startView as? SWPagePhotoView
            {
                let rects = SWDragManager.sharedManager().photoViewRects
                let views = rects.filter({$0.rect.contains(point)})
                
                if let targetView = views.valueAt(0)?.view
                {
                    //移到自身上
                    if targetView == startView
                    {
                        exchangeCancel()
                    }
                    else
                    {
                        exchangePhoto(startView, endView:targetView)
                    }
                }
                else if SWDragManager.sharedManager().deleteViewRect.contains(point)
                {
                    pagePhotoViewDelete(startView)
                }
                
            }//end startView
            
        }
        else if recognizer.state == .cancelled
        {
            SWDragManager.sharedManager().hideCursor()
            SWDragManager.sharedManager().deleting = false
            exchangeCancel()
        }
    }
    
    @objc private func backgroundTapped()
    {
        if SWDragManager.sharedManager().deleting
        {
            SWDragManager.sharedManager().deleting = false
        }
    }
    
    @objc private func labelTapped(_ recognizer:UITapGestureRecognizer)
    {
        if let label = recognizer.view as? UILabel,
           let text = page?.texts?.flatMap({$0 as? SWText}).valueAt(label.tag)
        {
            _popupTextInput.confirmCallback = {[weak self] content in
                self?.setLabelText(label, content: content)
                text.text = content
                self?.save()
                self?.addGenerationTask()
            }
            _popupTextInput.defaultText = text.text ?? ""
            _popupTextInput.show()
        }
    }
    
    @objc private func pageUpdatedNotification(_ notification:Notification)
    {
        if let aPageID = notification.userInfo?[SWKey.pageID] as? String,
            let pageID = page?.pageID,aPageID != "" && pageID == aPageID
        {
            updateAllPhotoView()
        }
    }
    
    @objc private func photoUpdatedNotification(_ notification:Notification)
    {
        if let imageID = notification.userInfo?[SWKey.imageID] as? String,
           let page = page,imageID != "" && page.containsPhoto(imageID: imageID)
        {
            updatePhotoView(imageID)
        }
    }
    
    @objc private func pageCompletedManualNotification(_ notification:Notification)
    {
        if let aPageID = notification.userInfo?[SWKey.pageID] as? String,
            let pageID = page?.pageID,aPageID != "" && pageID == aPageID
        {
            updateAllPhotoView()
        }
    }
    
    
}
